package com.ry.novel.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ry.novel.bean.AuthorHolder;
import com.ry.novel.bean.UserHolder;
import com.ry.novel.enums.NovelConst;
import com.ry.novel.enums.ResponseStatus;
import com.ry.novel.model.dto.AuthorInfo;
import com.ry.novel.model.dto.UserInfo;
import com.ry.novel.model.resp.Result;
import com.ry.novel.service.AuthorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ry
 * @since 2022-01-25 09:50
 **/
@Component
public class AuthorInterceptor implements HandlerInterceptor {
    @Autowired
    private AuthorService authorService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfo userInfo = UserHolder.userInfo.get();
        //检查它是否为作者，如果不是作者就应该注册作者信息
        //不是作者的话，填写信息成为作者
        AuthorInfo authorInfo = authorService.isAuthor(userInfo.getId());
        if (null == authorInfo) {
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setCharacterEncoding("utf8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(Result.fail(ResponseStatus.NOT_REGISTER_AUTHOR)));

            return false;
        }

        if (authorInfo.getState().equals(NovelConst.AUTHOR_STATE_FORBIDDEN)){
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setCharacterEncoding("utf8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(Result.fail(ResponseStatus.AUTHOR_STATE_FORBIDDEN)));

            return false;
        }

        AuthorHolder.authorInfo.set(authorInfo);


        return true;
    }
}
